package com.sunday.electric.receiver;

import android.annotation.SuppressLint;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.NotificationCompat;
import android.util.Log;

import com.google.gson.Gson;
import com.igexin.sdk.PushConsts;
import com.sunday.common.logger.Logger;
import com.sunday.common.model.ResultDO;
import com.sunday.common.utils.Constants;
import com.sunday.electric.R;
import com.sunday.electric.entity.PushModel;
import com.sunday.electric.http.ApiClient;
import com.sunday.electric.ui.MainActivity;
import com.sunday.electric.utils.SharePerferenceUtils;
import com.sunday.electric.utils.SystemUtils;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

//import com.sunday.electric.entity.PushModel;

@SuppressLint("NewApi")
/**
 * 接收到信息，进行解析
 * @author pangzf
 * @blog:http://blog.csdn.net/pangzaifei/article/details/43023625
 * @github:https://github.com/pangzaifei/zfIMDemo
 * @qq:1660380990
 * @email:pzfpang451@163.com
 */
public class PushMessageReceiver extends BroadcastReceiver {

    public static final String TAG = PushMessageReceiver.class.getSimpleName();
    public static final int NOTIFY_ID = 0x000;
    public static final String RESPONSE = "response";
    public static int mNewNum = 0;// 通知栏新消息条目，我只是用了一个全局变量，
    private Gson gson = new Gson();


    @Override
    public void onReceive(Context context, Intent intent) {
       /* if(intent.getAction().equals(ChatService.PUSH_MESSAGE)){
            String data = intent.getStringExtra("data");
            HashMap<String,String> model = BaseApplication.getInstance().getGson().fromJson(data,HashMap.class);
            showNotify(context,model.get("content"));
            Call<ResultDO> call = ApiClient.getIMAdapter().removeMsg("removeMessage",model.get("id"));
            call.enqueue(new Callback<ResultDO>() {
                @Override
                public void onResponse(Call<ResultDO> call, Response<ResultDO> response) {

                }

                @Override
                public void onFailure(Call<ResultDO> call, Throwable t) {

                }
            });
        }

    }*/
        Bundle bundle = intent.getExtras();
        Logger.d("GetuiSdkDemo", "onReceive() action=" + bundle.getInt("action"));
        switch (bundle.getInt(PushConsts.CMD_ACTION)) {
            //添加其他case
            //.........
            case PushConsts.GET_CLIENTID:
                String cid = bundle.getString("clientid");
                boolean isLogin = SharePerferenceUtils.getIns().getBoolean(Constants.IS_LOGIN, false);
                if (isLogin) {
                    Call<ResultDO> call = ApiClient.getIMAdapter().uploadCid("initCid", SharePerferenceUtils.getIns().getUserId(), cid);
                    call.enqueue(new Callback<ResultDO>() {
                        @Override
                        public void onResponse(Call<ResultDO> call, Response<ResultDO> response) {

                        }

                        @Override
                        public void onFailure(Call<ResultDO> call, Throwable t) {

                        }
                    });
                }

                break;
            case PushConsts.GET_MSG_DATA:
                isLogin = SharePerferenceUtils.getIns().getBoolean(Constants.IS_LOGIN, false);
                if (!isLogin) {
                    return;
                }
                byte[] payload = bundle.getByteArray("payload");
                if (payload != null) {
                    String data = new String(payload);
                    try {
                        PushModel pushModel = gson.fromJson(data, PushModel.class);
//                        showNotify(context, pushModel.getMessage(), "http://www.163.com");
                        showNotify(context,pushModel.getMessage(),pushModel.getUrl());
                    } catch (Exception e) {
                        e.printStackTrace();
                    }

                }
                break;
        }
    }

    private void showNotify(Context context, String content, String url) {
        NotificationManager mNotificationManager = (NotificationManager) context.getSystemService(context.NOTIFICATION_SERVICE);
        NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(context);
        String packageName = context.getApplicationInfo().packageName;
        Intent intent = new Intent(context, MainActivity.class);
        PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, getIntent(context, url), PendingIntent.FLAG_UPDATE_CURRENT);
        mBuilder.setContentTitle("作业安全风险管控移动端")//设置通知栏标题
                .setContentText(content)
                .setContentIntent(pendingIntent) //设置通知栏点击意图
//	.                   setNumber(number) //设置通知集合的数量
                .setTicker("作业安全风险管控移动端") //通知首次出现在通知栏，带上升动画效果的
                .setWhen(System.currentTimeMillis())//通知产生的时间，会在通知信息里显示，一般是系统获取到的时间
                .setPriority(Notification.PRIORITY_DEFAULT) //设置该通知优先级
                .setAutoCancel(true)//设置这个标志当用户单击面板就可以让通知将自动取消
                .setOngoing(false)//ture，设置他为一个正在进行的通知。他们通常是用来表示一个后台任务,用户积极参与(如播放音乐)或以某种方式正在等待,因此占用设备(如一个文件下载,同步操作,主动网络连接)
                .setDefaults(Notification.DEFAULT_ALL)//向通知添加声音、闪灯和振动效果的最简单、最一致的方式是使用当前的用户默认设置，使用defaults属性，可以组合
                        //Notification.DEFAULT_ALL  Notification.DEFAULT_SOUND  DEFAULT_VIBRATE 添加声音 // requires VIBRATE permission
                .setSmallIcon(R.mipmap.applogo);//设置通知小ICON
        mNotificationManager.notify(NOTIFY_ID, mBuilder.build());
    }

    private Intent getIntent(Context context, String url) {
        if (SystemUtils.isAppAlive(context, "com.sunday.electric")) {
            Log.i("NotificationReceiver", "the app process is alive");
            Intent mainIntent = new Intent(context, MainActivity.class);
            mainIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
/*
            Intent detailIntent = new Intent(context, WebViewActivity.class);*/
            mainIntent.putExtra("url", url);
            return mainIntent;
        } else {
            Log.i("NotificationReceiver", "the app process is dead");
            Intent launchIntent = context.getPackageManager().
                    getLaunchIntentForPackage("com.sunday.electric");
            launchIntent.setFlags(
                    Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);
            launchIntent.putExtra("url", url);
            return launchIntent;
        }
    }

}
